import 'dart:async';

import 'package:common_tool/ping_tool.dart';
import 'package:flutter/foundation.dart';
import 'package:get_storage/get_storage.dart';

const Duration interval = Duration(milliseconds: 60 * 1000 * 10);
const Duration debugInterval = Duration(milliseconds: 30 * 1000);
const Duration longInterval = Duration(minutes: 60 * 24);

const String lastDayUploadTimeKey = 'lastDayUploadTimeKey';

const String actionTypeHeartbeat = 'Heartbeat';
const String actionTypeSummary = 'Summary';

typedef UploadCallback = Future<bool> Function();

class UploadManager {

  static Timer? timer;

  /// 短频上报回调（10min）
  static UploadCallback? shortIntervalUploadCallback;
  /// 长频上报回调（1d）
  static UploadCallback? longIntervalUploadCallback;

  static start() {

    timer = Timer.periodic(interval, (timer) async {
      /// 短频上报记录
      if (shortIntervalUploadCallback != null) {
        final uploadRes = await shortIntervalUploadCallback!();
        if (uploadRes) {
          PingTool.savedDataList = [];
        }
      }
      /// 长频上报记录
      if (longIntervalUploadCallback == null) {
        return;
      }
      /// 如果没有上次的记录时间，就直接上传
      if (lastDayUploadTime == null) {
        callLongIntervalUpload();
      } else {
        bool isAnotherDay = DateTime.now().millisecondsSinceEpoch - lastDayUploadTime! > longInterval.inMilliseconds;
        if (isAnotherDay) {
          callLongIntervalUpload();
        }
      }
    });

  }

  /// 上报长频日志
  static void callLongIntervalUpload() async {
    final uploadRes = await longIntervalUploadCallback!();
    if (uploadRes) {
      lastDayUploadTime = DateTime.now().millisecondsSinceEpoch;
      PingTool.savedDataList = [];
    }
  }

  /// 缓存上次单日上报的时间
  static int? get lastDayUploadTime => GetStorage().read(lastDayUploadTimeKey);
  static set lastDayUploadTime(int? lastDayUploadTime) =>
      GetStorage().write(lastDayUploadTimeKey, lastDayUploadTime);

}